package com.rub.android.jetpack

import android.view.View
import android.widget.ProgressBar
import android.widget.Toast
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.paging.LoadState
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.rub.android.R
import com.rub.android.base.BaseActivity
import com.rub.android.jetpack.adapter.FooterAdapter
import com.rub.android.jetpack.adapter.RepoAdapter
import com.rub.android.jetpack.viewmodel.GithubViewModel
import com.rub.android.widget.InjectorUtil
import kotlinx.coroutines.launch
import kotlinx.coroutines.flow.collect

class GithubActivity : BaseActivity() {

    override fun getLayoutId(): Int = R.layout.activity_github
    private val repoAdapter by lazy { RepoAdapter() }

    private val viewModel by lazy {
        ViewModelProvider(
            this,
            InjectorUtil.getGithubViewModelFactory()
        ).get(GithubViewModel::class.java)
    }

    override fun initView() {
        val recyclerView = findViewById<RecyclerView>(R.id.recycler_view)
        val progressBar = findViewById<ProgressBar>(R.id.progress_bar)

        recyclerView.layoutManager = LinearLayoutManager(this)
        recyclerView.adapter =
            repoAdapter.withLoadStateFooter(FooterAdapter { repoAdapter.retry() })

        //根据关键字去查询
        val keyword = "Kotlin"

        lifecycleScope.launch {
            viewModel.getPagingData(keyword).collect { pagingData ->
                repoAdapter.submitData(pagingData)
            }
        }

        repoAdapter.addLoadStateListener {
            when (it.refresh) {
                is LoadState.NotLoading -> {
                    progressBar.visibility = View.INVISIBLE
                    recyclerView.visibility = View.VISIBLE
                }
                is LoadState.Loading -> {
                    progressBar.visibility = View.VISIBLE
                    recyclerView.visibility = View.INVISIBLE
                }
                is LoadState.Error -> {
                    val state = it.refresh as LoadState.Error
                    progressBar.visibility = View.INVISIBLE
                    Toast.makeText(this, "Load Error: ${state.error.message}", Toast.LENGTH_SHORT)
                        .show()
                }
            }
        }
    }

}


